<!-- 门店入驻 -->
<template>
	<view class="apply-commission-wrap page_box">

		<!-- 表单 -->

		<view class="apply-form content_box">
			<u-form :model="model" :rules="rules" ref="uForm" :errorType="errorType">
				<u-form-item :labelStyle="labelStyle" label-width="150" label-position="left" label="门店名称"
					prop="shop_name">
					<u-input placeholder="请输入门店名称" :placeholderStyle="placeholderStyle" v-model="model.shop_name"
						type="text" input-align="right"></u-input>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" label-width="150" label-position="left" label="餐厅分类">
					<u-input type="select" placeholder="请选择餐厅分类" disabled :placeholderStyle="placeholderStyle"
						v-model="reg_cate" input-align="right" @click="onSelect('restaurant')"></u-input>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" label-width="150" label-position="left" label="省市区"
					prop="address">
					<u-input type="select" placeholder="请选择省市区" disabled :placeholderStyle="placeholderStyle"
						v-model="model.address" input-align="right" @click="onSelect('address')"></u-input>
					<u-picker mode="region" v-model="showAddressModal" :area-code='["13", "1303", "130304"]'
						@confirm="saveAddress" @cancle="showAddressModal=false"></u-picker>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" label-width="150" label-position="left" label="详细地址"
					prop="shop_address">
					<view class="">
						<u-input type="textarea" placeholder="请输入详细地址~" input-align="right"
							:placeholderStyle="placeholderStyle" v-model="model.shop_address"></u-input>
					</view>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" right-icon="map-fill" :right-icon-style="{color:'#4CB89D'}"
					label-width="150" label-position="left" label="经纬度" prop="area">
					<u-input type="text" disabled v-model="model.area" placeholder="请点击定位" input-align="right"
						:placeholderStyle="placeholderStyle" @click="chooseLocation">
					</u-input>
				</u-form-item>
				<!-- 	<u-form-item :labelStyle="labelStyle" label-position="left" label="充值金额" prop="phone" label-width="150">
					<u-input placeholder="请输入充值金额" :placeholderStyle="placeholderStyle" v-model="model.phone"
						type="number" input-align="right"></u-input>
				</u-form-item> -->
				<u-form-item :labelStyle="labelStyle" label-width="150" label-position="left" label="人均消费"
					prop="shop_avg">
					<u-input placeholder="请输入人均消费" :placeholderStyle="placeholderStyle" v-model="model.shop_avg"
						type="text" input-align="right"></u-input>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" label-width="150" label-position="left" label="结算折扣"
					prop="discount">
					<u-input placeholder="请输入结算折扣" :placeholderStyle="placeholderStyle" v-model="model.discount"
						type="text" input-align="right"></u-input>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" label-position="left" label="客服电话" prop="shop_mobile"
					label-width="150">
					<u-input placeholder="请输入客服电话" :placeholderStyle="placeholderStyle" v-model="model.shop_mobile"
						type="number" input-align="right"></u-input>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" label-position="top" label="餐厅标签" label-width="150">
					<view class="tags-box">
						<view class="tags">
							<u-tag v-for="(item,index) in tagsList" :key="index" :text="item" mode="light" closeable
								shape="circle" type="error" @close="deltag(deltag)" />
						</view>
						<view class="u-flex">
							<view style="width: 80%;margin-right: 6%;">
								<u-input placeholder="输入餐厅关键字，每标签最多4字，最多4个标签" :placeholderStyle="placeholderStyle"
									input-align="left" v-model="tagInfo" maxlength="4"></u-input>
							</view>
							<u-button type="success" size="mini" @click="saveTag()">确定</u-button>
						</view>
					</view>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" label-width="150" label-position="left" label="营业时间"
					prop="yingye_times">
					<u-input type="select" :select-open="selectShow" v-model="model.yingye_times" placeholder="请选择营业时间"
						:placeholderStyle="placeholderStyle" input-align="right" @click="onSelect('time')"></u-input>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" prop="images" label="营业执照" label-position="top" label-width="150"
					:borderBottom="true">
					<u-upload :placeholderStyle="placeholderStyle" :showProgress="false"
						@on-uploaded="uploadSuccess($event, 'zizhi_images')"
						@on-remove="uploadRemove($event, 'zizhi_images')" :action="action"
						:file-list="fileImages_zizhi_images" width="148" height="148" maxCount="9"></u-upload>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" prop="images" label="餐厅头像" label-position="top" label-width="150"
					:borderBottom="true">
					<u-upload :placeholderStyle="placeholderStyle" :showProgress="false"
						@on-uploaded="uploadSuccess($event, 'shop_image')"
						@on-remove="uploadRemove($event, 'shop_image')" :action="action"
						file-list="fileImages_shop_image" width="148" height="148" maxCount="1"></u-upload>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" prop="images" label="餐厅轮播图片" label-position="top"
					label-width="150" :borderBottom="true">
					<u-upload :placeholderStyle="placeholderStyle" :showProgress="false"
						@on-uploaded="uploadSuccess($event, 'images')" @on-remove="uploadRemove($event, 'images')"
						:action="action" :file-list="fileImages_images" width="148" height="148">
					</u-upload>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" :border-bottom="false" prop="images" label="餐厅详情图片"
					label-position="top" label-width="150">
					<u-upload :placeholderStyle="placeholderStyle" :showProgress="false"
						@on-uploaded="uploadSuccess($event, 'tao_content')"
						@on-remove="uploadRemove($event, 'tao_content')" :action="action"
						:file-list="fileImages_tao_content" width="148" height="148"></u-upload>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" :border-bottom="false" prop="images" label="使用说明图片"
					label-position="top" label-width="150">
					<u-upload :placeholderStyle="placeholderStyle" :showProgress="false"
						@on-uploaded="uploadSuccess($event, 'use_content')"
						@on-remove="uploadRemove($event, 'use_content')" :action="action"
						:file-list="fileImages_use_content" width="148" height="148"></u-upload>
				</u-form-item>
				<view class="button-box">
					<view class="u-flex u-row-center u-col-center"><button class="u-reset-button save-btn"
							@tap="onSubmit" :disabled="isFormEnd">确定</button></view>
				</view>

			</u-form>
		</view>

		<!-- 弹窗 -->
		<u-select v-if="selectShow" :mode="selectMode" :list="selectList" v-model="selectShow" @confirm="selectConfirm">
		</u-select>

		<!-- 选择星期 -->
		<u-popup v-model="showWeeksModal" safe-area-inset-bottom mode="bottom">
			<view class="week-modal">
				<view class="u-flex u-row-between u-p-x-30 week-modal--head ">
					<view></view>
					<view class="action text-green" @tap="saveWeekModal">确定</view>
				</view>
				<view class="u-flex u-flex-wrap u-p-x-30 u-p-y-30 week-modal--content">
					<view v-for="(item, index) in weekcheckbox" class="week-btn " :key="index">
						<button @tap="onSelectWeek(index)" class="cu-btn"
							:class="!item.checked ? 'line-green' : 'bg-green'">{{ item.name }}</button>
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 选择餐厅分类 -->
		<u-select v-model="showRestaurantClassificationModal" mode="single-column" :list="restaurantClassificationckbox"
			value-name="store_cate_id" label-name="name" @confirm="saveconfirmRestaurant"></u-select>

		<!-- 权限验证 -->
		<u-popup v-model="showNotice" mode="center" border-radius="20">
			<view class="notice-modal">
				<view class="img-wrap">
					<image class="notice-img" :src="authNotice.img" mode=""></image>
				</view>
				<view class="notice-title">{{ authNotice.title }}</view>
				<view class="notice-detail">{{ authNotice.detail || '' }}</view>
				<button class="u-reset-button notice-btn"
					@tap="onAuthBtn(authNotice.btnPath)">{{ authNotice.btnText }}</button>
				<button class="u-reset-button back-btn" @tap="$Router.back()">返回</button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import Auth from '@/shopro/permission/index.js';
	import {
		BASE_URL
	} from '@/env'
	import {
		mapMutations,
		mapActions,
		mapState,
		mapGetters
	} from 'vuex';
	import {
		MAP_KEY
	} from '@/env.js';
	export default {
		components: {},
		data() {
			return {
				action: BASE_URL + '/api/common/upload',
				showNotice: false,
				showWeeksModal: false, //星期弹窗
				showRestaurantClassificationModal: false, //餐厅分类弹窗
				showAddressModal: false, //省市区弹窗
				isFormEnd: false,
				// 餐厅分类
				restaurantClassificationckbox: [],
				authNotice: {},
				// 表单
				errorType: ['message'],
				selectShow: false,
				selectMode: 'mutil-column', // single-column, mutil-column, mutil-column-auto
				selectType: '',
				selectList: [],
				labelStyle: {
					'font-size': '28rpx',
					'font-weight': '500',
					color: '#333'
				},
				placeholderStyle: 'font-size: 28rpx;color:#c4c4c4;textAlign:right;',
				model: {
					shop_name: '', //门店名称
					reg_cate: '', //餐厅分类
					province_name: '', //省
					city_name: '', //市区
					area_name: '', //1区
					shop_address: '', //详情地址
					latitude: '', //纬度
					longitude: '', //经度					
					shop_avg: '', //人均消费ID
					discount: null, //结算折扣
					shop_mobile: '', //客服电话
					shop_tags: '', //店铺标签
					yingye_times: '', //营业时间
					zizhi_images: [], //营业执照
					shop_image: '', //餐厅头像
					images: [], //餐厅轮播图
					tao_content: [], //餐厅详情图
					use_content: [], //使用说明图
					id: '',
					address: '',
					area: '',
				},
				fileImages_zizhi_images: null,
				fileImages_shop_image: null,
				fileImages_images: null,
				fileImages_tao_content: null,
				fileImages_use_content: null,
				tagInfo: '',
				tagsList: [],
				reg_cate: '',
				rules: {
					shop_name: [{
						required: true,
						message: '请输入门店名称',
						trigger: ['change', 'blur']
					}],
					reg_cate: [{
						required: true,
						message: '请选择餐厅分类',
						trigger: ['change', 'blur']
					}],
					address: [{
						required: true,
						message: '请选择省市区',
						trigger: ['change', 'blur']
					}],
					shop_address: [{
						required: true,
						message: '请输入详细地址',
						trigger: ['change', 'blur']
					}],
					area: [{
						required: true,
						message: '请定位所在地区',
						trigger: ['change', 'blur']
					}],
					shop_avg: [{
						required: true,
						message: '请输入人均消费',
						trigger: ['change', 'blur']
					}],
					discount: [{
						required: true,
						message: '请输入结算折扣',
						trigger: ['change', 'blur']
					}],
					shop_tags: [{
						required: true,
						message: '请输入餐厅标签',
						trigger: ['change', 'blur']
					}],
					shop_mobile: [{
							required: true,
							message: '请输入客服电话',
							trigger: ['change', 'blur']
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value);
							},
							message: '客服电话不正确',
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ['change', 'blur']
						}
					],
					yingye_times: [{
						required: true,
						message: '请选择营业时间',
						trigger: ['change', 'blur']
					}],
					// address[{
					// 	required: true,
					// 	message: '请选择省市区',
					// 	trigger: ['change', 'blur']
					// }],
					weeks: [{
						required: true,
						message: '请选择营业天数',
						trigger: ['change', 'blur']
					}],

				}
			};
		},
		computed: {
			...mapGetters(['initStore']),
			selectWorkerTime() {
				let mArr = [];
				for (let i = 0; i <= 24; i++) {
					let t = String(i).padStart(2, '0');
					mArr.push({
						value: `${t}:00`,
						label: `${t}:00`
					}, {
						value: `${t}:30`,
						label: `${t}:30`
					});
				}
				mArr.pop();
				return [mArr, mArr];
			}
		},
		onLoad() {
			this.getStoreInfo();
			this.getStoreType()
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			getStoreType() {
				let that = this;
				that.$http_business('store.typeList').then(res => {
					if (res.code == 1) {
						this.restaurantClassificationckbox = res.data;
					}
				});
			},
			// 选择星期
			saveWeekModal() {
				this.showWeeksModal = false;
				let arr = [];
				let arr2 = [];
				this.weekcheckbox.forEach(item => {
					if (item.checked) {
						arr.push(item.value);
						arr2.push(item.name);
					}
				});
				this.model.openweeks = arr.join(',');
				this.model.weeks = arr2.join(',');
			},
			// 选择餐厅分类
			saveconfirmRestaurant(e) {
				this.model.reg_cate = e[0].value;
				this.reg_cate = e[0].label;
			},
			// 选择省市区
			saveAddress(e) {
				console.log(e);
				this.model.province_name = e.province.label;
				this.model.city_name = e.city.label;
				this.model.area_name = e.area.label;
				this.model.address = this.model.province_name + this.model.city_name + this.model.area_name
			},

			// 选择星期
			onSelectWeek(index) {
				this.weekcheckbox[index].checked = !this.weekcheckbox[index].checked;
			},


			// 弹窗按钮
			onAuthBtn(path) {
				path &&
					this.$Router.push({
						path: path
					});
				this.showNotice = false;
			},

			// 上传图片成功
			uploadSuccess(e, type) {
				console.log("e:", e)

				switch (type) {
					case 'zizhi_images':
						this.model.zizhi_images = [];
						e.forEach(item => {
							this.model.zizhi_images.push(item.response.data.url);
							// this.model.zizhi_images = this.fileImages_zizhi_images
						});
						break;
					case 'shop_image':
						this.model.shop_image = '';
						e.forEach(item => {
							this.model.shop_image = item.response.data.url;
							// this.model.shop_image = this.fileImages_shop_image.join(',')
						});
						break;
					case 'images':
						this.model.images = [];
						e.forEach(item => {
							this.model.images.push(item.response.data.url);
							// this.model.images = this.fileImages_images
						});
						break;
					case 'tao_content':
						this.model.tao_content = [];
						e.forEach(item => {
							this.model.tao_content.push(item.response.data.url);
							// this.model.tao_content = this.fileImages_tao_content
						});
						break;
					case 'use_content':
						this.model.use_content = [];
						e.forEach(item => {
							this.model.use_content.push(item.response.data.url);
							// this.model.tao_content = this.fileImages_tao_content
						});
						break;
					default:
						return;
				}
			},

			// 移除图片
			uploadRemove(index, type) {
				switch (type) {
					case 'zizhi_images':
						this.model.zizhi_images.splice(index, 1);
						break;
					case 'shop_image':
						this.model.shop_image = '';
						break;
					case 'images':
						this.model.images.splice(index, 1);
						break;
					case 'tao_content':
						this.model.tao_content.splice(index, 1);
						break;
					case 'use_content':
						this.model.use_content.splice(index, 1);
						break;
					default:
						return;
				}
			},

			// 地址选择
			async chooseLocation() {
				let authState = await new Auth('userLocation').check();
				authState &&
					uni.chooseLocation({
						success: res => {
							console.log("res:", res)
							this.model.latitude = res.latitude;
							this.model.longitude = res.longitude;
							this.model.area = this.model.latitude + ',' + this.model.longitude
							// this.getLocationInfo();
						},
						fail: err => {
							console.log(err);
						}
					});
			},

			//逆坐标解析
			async getLocationInfo() {
				this.chooseAddress = '定位中...';
				const [error, res] = await uni.request({
					url: `https://restapi.amap.com/v3/geocode/regeo?location=${this.model.longitude},${this.model.latitude}&key=${MAP_KEY}`
				});
				if (res.data.status === '1') {
					const addressComponent = res.data.regeocode.addressComponent;
					// this.model.area_id = addressComponent.adcode;
					// this.model.area =
					// 	`${addressComponent.province}-${addressComponent.city.length ? addressComponent.city : addressComponent.province}-${addressComponent.district}`;
					this.model.address = res.data.regeocode.formatted_address.replace(
						`${addressComponent.province}${addressComponent.city}${addressComponent.district}`, '');
				} else {
					console.log('%c逆地址解析失败，请检查是否在env中配置地图key', 'color:green;background:yellow');
				}
			},

			onSelect(type) {
				this.selectType = type;
				switch (type) {
					case 'time':
						this.selectShow = true;
						this.selectMode = 'mutil-column';
						this.selectList = this.selectWorkerTime;
						break;
					case 'week':
						this.showWeeksModal = true;
						break;
					case 'restaurant':
						this.showRestaurantClassificationModal = true;
						break;
					case 'address':
						this.showAddressModal = true;
						break;
					case 'discount':
						this.showDiscountModal = true;
						break;
					default:
						return;
				}
			},

			// 选择时间
			selectConfirm(e) {
				switch (this.selectType) {
					case 'time':
						this.model.yingye_times = '';
						e.map((val, index) => {
							this.model.yingye_times += this.model.yingye_times == '' ? val.label : ' - ' + val
								.label;
						});
						break;
					default:
						return;
				}
			},

			// 保存标签
			saveTag() {
				if (this.tagsList.length <= 4) {
					this.tagsList.push(this.tagInfo);
					this.model.shop_tags = this.tagsList.join(",")
					this.tagInfo = ''
				} else {
					this.$u.toast('餐厅标签最多可上传4个！')
				}
			},
			// 删除标签
			deltag(index) {
				console.log(index)
				this.tagsList.splice(index, 1);
				this.model.shop_tags = this.tagsList.join(",")
			},

			// 门店详情
			getStoreInfo() {
				let that = this;
				that.$http('store.shopInfo').then(res => {
					if (res.code === 1) {
						res.data && this.authStatus(res.data);
					}
				});
			},
			// 跳转门店协议
			toProtocol() {
				this.initStore.protocol && this.jump('/pages/public/richtext', {
					id: this.initStore.protocol
				})
			},

			// 初始化model
			initModel() {
				// 构建星期
				let weeksArr = this.model.openweeks.split(',');
				let weekTextArr = [];
				this.weekcheckbox.forEach(item => {
					if (weeksArr.includes(item.value)) {
						weekTextArr.push(item.name);
						item.checked = true;
					}
				});
				this.model.weeks = weekTextArr.join(',');
				// 构建省市区
				if (this.model.province_name) {
					this.model.area = `${this.model.province_name}-${this.model.city_name}-${this.model.area_name}`;
				}
				if (this.model.images) {
					this.model.images.forEach(item => {
						this.model.fileImages.push({
							url: item
						});
					});
				}
				// 协议
				this.$set(this.model, 'agreement', false);
			},

			// 状态鉴权
			authStatus(data) {
				switch (String(data.status)) {
					case '0':
						this.showNotice = true;
						this.model = {
							...this.model,
							...data
						};
						this.initModel();
						this.authNotice = {
							img: this.$IMG_URL + '/imgs/commission/auth_check.png',
							title: '正在审核中',
							detail: data.status_msg,
							btnText: '修改信息',
							btnPath: ''
						};
						break;
					case '-1':
						this.showNotice = true;
						this.model = {
							...this.model,
							...data
						};
						this.initModel();
						this.authNotice = {
							img: this.$IMG_URL + '/imgs/commission/auth_reject.png',
							title: '您的申请已被驳回！',
							detail: data.status_msg,
							btnText: '重新申请',
							btnPath: ''
						};
						break;
					case '1':
						this.showNotice = false;
						break;

					default:
				}
			},

			// 申请门店
			applyStore() {
				let that = this;
				this.isFormEnd = false;
				that.$http_business('store.add', that.model, '提交中...').then(res => {
					this.isFormEnd = true;
					if (res.code === 1) {
						//  #ifdef MP-WEIXIN
						this.$store.commit('subscribeMessage', 'storeApply');
						//  #endif
						uni.showToast({
							title: res.msg,
							success: () => {
								that.$Router.back();
							}
						});
					}
				});
			},

			// 提交
			onSubmit() {
				let that = this;
				console.log("啊哈哈哈：", that.model)
				if (!that.model.reg_cate) {
					this.$u.toast('请选择餐厅分类  ');
					return;
				}
				if (!this.model.shop_tags) {
					this.$u.toast('请添加餐厅标签  ');
					return;
				}
				if (!that.model.zizhi_images) {
					this.$u.toast('请上传营业执照');
					return;
				}
				if (!that.model.shop_image) {
					this.$u.toast('请上传餐厅头像');
					return;
				}
				if (!that.model.images) {
					this.$u.toast('请上传餐厅轮播图 ');
					return;
				}
				if (!that.model.tao_content) {
					this.$u.toast('请上传餐厅详情图  ');
					return;
				}
				if (!that.model.use_content) {
					this.$u.toast('请上使用说明图  ');
					return;
				}
				this.$refs.uForm.validate(valid => {
					if (valid) {
						this.applyStore();
					} else {
						this.$u.toast('请完善表单');
					}
				});
			},
			jump(path, parmas) {
				this.$Router.push({
					path: path,
					query: parmas
				});
			}
		}
	};
</script>

<style lang="scss">
	.apply-commission-wrap {
		background-color: #F8F8F8;
		// padding-bottom: 150rpx;
	}

	// 表单
	.apply-form {
		width: 100%;
		background: #ffffff;
		border-radius: 20rpx;
		padding: 30rpx;
		padding-bottom: 150rpx;

		.agreement {
			margin-top: 20rpx;

			.agreement-text {
				font-size: 24rpx;
				font-weight: 500;
				color: #4cb89d;
			}
		}

		.button-box {
			background-color: #fff;
			position: fixed;
			left: 0;
			bottom: 0;
			width: 100%;
			margin-top: 30rpx;
			border-top: 24rpx solid #F8F8F8;
			z-index: 9999;
		}

		.save-btn {
			width: 690rpx;
			line-height: 86rpx;
			background: #FC5351;
			border-radius: 43rpx;
			font-weight: 500;
			color: #ffffff;
			margin: 30rpx 0;
		}
	}

	// 星期
	.week-modal {
		.week-modal--head {
			height: 100rpx;
			border-bottom: 1rpx solid $u-border-color;

			.text-cancel {
				color: #ccc;
			}

			.text-green {
				color: #18b566;
			}
		}

		.week-modal--content {
			.week-btn {
				margin-right: 56rpx;
				margin-bottom: 30rpx;

				&:nth-of-type(4n) {
					margin-right: 0;
				}
			}
		}
	}

	// 提示
	.notice-modal {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		width: 612rpx;
		min-height: 658rpx;
		background: #ffffff;
		padding: 30rpx;
		border-radius: 20rpx;

		.img-wrap {
			margin-bottom: 50rpx;

			.notice-img {
				width: 180rpx;
				height: 170rpx;
			}
		}

		.notice-title {
			font-size: 35rpx;
			font-weight: bold;
			color: #46351b;
			margin-bottom: 28rpx;
		}

		.notice-detail {
			font-size: 28rpx;
			font-weight: 400;
			color: #999999;
			line-height: 36rpx;
			margin-bottom: 50rpx;
		}

		.notice-btn {
			width: 492rpx;
			height: 70rpx;
			line-height: 70rpx;
			background: linear-gradient(90deg, #2dae9c, #6bc29e);
			box-shadow: 0 7rpx 11rpx 2rpx rgba(61, 179, 156, 0.34);
			border-radius: 35rpx;
			font-size: 28rpx;
			font-weight: 500;
			color: #ffffff;
			margin-bottom: 10rpx;
		}

		.back-btn {
			width: 492rpx;
			height: 70rpx;
			line-height: 70rpx;
			font-size: 28rpx;
			font-weight: 500;
			color: #3ab29c;
			background: none;
		}
	}

	.tags-box {
		position: relative;

		.tags {
			position: absolute;
			top: -110%;
			left: 20%;
		}
	}

	/deep/ .u-form-item__message {
		text-align: right;
	}
</style>
